<template>
  <div class="shouj">
    <div class="app" v-for="rider in list">
      <span class="qu"> {{ rider.startingPoint }} </span><br><br><br>
      <span class="xiao1">全程<font color="#6495ed">{{rider.distance}}</font>公里</span><br>
      <button class="butt" @click="xingc">行程信息</button>
      <hr>
      <!--      <span class="xiao2">请在<font color="red">10分钟</font>内到达出发点</span>-->
    </div>
    <div id="container"></div>
    <div id="panel"></div> <!-- 添加面板 -->
    <div class="shuju">
      <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
        <div class="didian" v-for="rider in list">
          <div class="phones">
            <span class="shuzi">{{ rider.phoneNumber.slice(-4) }}</span><br>
            <span class="weihao">尾号</span>
          </div>
          <span>{{ rider.startingPoint }}</span><br>
          <span>{{ rider.terminal }}</span>
          <button @click="showRoute(rider)">显示路线</button> <!-- 新增按钮 -->
          <button @click="drawRouteToStartingPoint(rider)">显示当前位置到起点的路线</button>
        </div>
      </ul>
      <span class="el-icon-chat-dot-square" @click="tochat"></span>
      <a :href="'tel:'+400456123"><i class="el-icon-phone"></i></a>
    </div>
    <div class="group">
      <button @click="handleArrive" class="daoda">到达出发点</button>
      <button @click="handlePickup" class="jiedao" disabled>接到乘客</button>
    </div>
    <el-dialog title="请询问乘客乘车码" :visible.sync="carcodeShow">
      <el-form>
        <el-form-item label="乘车码">
          <el-input v-model="carcode"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="carcodeShow = false">取 消</el-button>
        <el-button type="primary" @click="tomudidi()">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";

window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "23a30393a855e07d2ba7621ac8e4e6d2",
};

export default {
  name: "HomeView",
  data() {
    return {
      // 乘车码弹框（默认：未开启）
      carcodeShow: false,
      // 乘车码
      carcode: "",
      list: {},
      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      Geolocation: null,
      Geocoder: null,
      // 搜索提示
      AutoComplete: null,
      // 缩放控件
      ToolBar: null,
      // 地图放大镜
      HawkEye: null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      form: {
        lng: "116.397427",
        lat: "39.909302",
        address: '',
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      id: 0,
      // 新增：用于存储当前位置的经度
      currentLng: 116.21720503656424,
      // 新增：用于存储当前位置的纬度
      currentLat: 40.21813347249725,
      Scale: null,
    };
  },
  created() {
    this.initMap();
    this.getListSync(); // 修改为调用同步获取列表的方法
    this.sendCurrentPositionToBackend();
    this.id = sessionStorage.getItem("id")
  },
  methods: {
    tochat(){
      console.log("starting的list")
      console.log(this.list)
      localStorage.setItem('phone',JSON.stringify(this.list.phoneNumber));
      localStorage.setItem('did',JSON.stringify(this.list.did));
      this.$router.push("/chat");
    },

    // 显示当前位置到起点的路线
    drawRouteToStartingPoint(rider) {
      const startingPoint = rider.startingPoint;

      // 获取起点的经纬度
      this.getLatLng(startingPoint).then(startLatLng => {
        const currentLatLng = [this.currentLng, this.currentLat];

        // 计算两点之间的距离
        this.calculateDistance(currentLatLng, startLatLng);

        // 绘制路线
        this.drawRoute(currentLatLng, startLatLng);
      }).catch(error => {
        console.error("获取经纬度失败：", error);
      });
    },
    // 显示路线
    showRoute(rider) {
      const startingPoint = rider.startingPoint;
      const terminal = rider.terminal;

      // 获取起点和终点的经纬度
      this.getGeocode(startingPoint, terminal).then(({startLatLng, endLatLng}) => {
        // 计算两点之间的距离
        this.calculateDistance(startLatLng, endLatLng);

        // 绘制路线
        this.drawRoute(startLatLng, endLatLng);
      }).catch(error => {
        console.error("获取经纬度失败：", error);
      });
    },
    // 获取经纬度
    getGeocode(startingPoint, terminal) {
      return Promise.all([
        this.getLatLng(startingPoint),
        this.getLatLng(terminal)
      ]).then(([startLatLng, endLatLng]) => ({
        startLatLng,
        endLatLng
      }));
    },
    // 获取单个地址的经纬度
    getLatLng(address) {
      return new Promise((resolve, reject) => {
        this.geoCoder.getLocation(address, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const location = result.geocodes[0].location;
            resolve([location.lng, location.lat]);
          } else {
            reject(new Error('无法获取经纬度'));
          }
        });
      });
    },
    // 计算两点之间的距离
    calculateDistance(startLatLng, endLatLng) {
      AMapLoader.load({
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        plugins: ["AMap.Driving"]
      }).then((AMap) => {
        const driving = new AMap.Driving({
          map: this.map,
          panel: "panel"
        });

        driving.search(startLatLng, endLatLng, (status, result) => {
          if (status === 'complete') {
            console.log('驾车距离:', result.routes[0].distance, '米');
          } else {
            console.error('驾车搜索失败：', result);
          }
        });
      }).catch(e => {
        console.error(e);
      });
    },
    // 绘制路线
    drawRoute(startLatLng, endLatLng) {
      AMapLoader.load({
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        plugins: ["AMap.Driving"]
      }).then((AMap) => {
        const driving = new AMap.Driving({
          map: this.map,
          panel: "panel"
        });

        driving.search(startLatLng, endLatLng, (status, result) => {
          if (status === 'complete') {
            console.log('驾车搜索成功');
          } else {
            console.error('驾车搜索失败：', result);
          }
        });
      }).catch(e => {
        console.error(e);
      });
    },
    daoda() {
      this.$router.push('/destination')
    },
    tomudidi() {
      axios.post(`/jiedan/riderQueue/updateStatus?id=${this.id}`).then(res => {
        this.$router.push('/destination')
      })
    },
    // 接到乘客
    handlePickup() {
      this.carcodeShow = true;
      this.carcode = "";
    },
    // 到达出发点
    handleArrive() {
      // 到达出发点按钮点击事件处理
      this.$router.push('/setOut')
      console.log('已到达出发点');
      // 这里可以添加具体的逻辑，如更新状态、发送请求等
    },
    // 根据手机号查询到司机id
    async findDriverByTel() {
      const tel = JSON.parse(localStorage.getItem('login'));
      const response = await axios.post('personal/personal/findByTel?tel=' + tel);
      this.driverInfo = response.data;
      console.log(this.driverInfo);
      return this.driverInfo;
    },
    async getListSync() {
      try {
        // 先获取司机信息
        const driverInfo = await this.findDriverByTel();
        // 再根据司机信息获取列表数据
        const response = await axios.get(`/jiedan/riderQueue/findAll2?did=${this.driverInfo.id}` + "&id=" + this.id);
        this.list = response.data;
      } catch (error) {
        console.error("获取数据失败：", error);
      }
      await axios.post(`/jiedan/riderQueue/updateOrderType?id=${this.id}`)
    },
    reset() {
      this.keywords = '';
      this.form = {
        lng: "119.793098",
        lat: "31.91243",
        address: '',
      }
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    },
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "b17513b156700f5d461409278e81ffa7",
        version: "2.0",
        // 需要用到的插件
        plugins: ["AMap.Geocoder", "AMap.AutoComplete", "AMap.ToolBar", "AMap.HawkEye", "AMap.Geolocation", "AMap.Scale"],
      })
        .then((AMap) => {
          this.Geolocation = new AMap.Geolocation({
            position: {
              bottom: '20px',
              right: '20px'
            },
            enableHighAccuracy: true // 设置为高精度定位，可能会消耗更多电量和流量
          });
          this.map = new AMap.Map("container", {
            viewMode: "3D", // 是否为3D地图模式
            zoom: 10, // 初始化地图级别
            center: [this.form.lng, this.form.lat], // 初始化地图中心点位置
          });

          // 地址逆解析插件
          this.geoCoder = new AMap.Geocoder({
            city: "010", // 城市设为北京，默认：“全国”
            radius: 1000, // 范围，默认：500
          });

          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({city: "全国"});
          this.ToolBar = new AMap.ToolBar({
            position: {
              bottom: '210px',
              right: '35px'
            }
          });
          this.HawkEye = new AMap.HawkEye({
            position: {
              bottom: '110px',
              left: '35px'
            }
          });
          this.Scale = new AMap.Scale({
            position: {
              bottom: '20px',
              left: '20px'
            }
          });

          this.map.addControl(this.ToolBar);

          // 清除点
          this.removeMarker();
          // 标记点
          this.setMapMarker();

          // 点击获取经纬度;
          this.map.on("click", (e) => {
            // 获取经纬度
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            // 省略部分代码...
          });

          // 获取当前位置
          this.Geolocation.on('complete', (data) => {
            console.log('获取当前位置成功：', data);
            // 存储当前位置的经度和纬度
            this.currentLng = data.position.lng;
            this.currentLat = data.position.lat;
            alert("纬度" + this.currentLat);
            alert("经度" + this.currentLng);

            // 发送当前位置到后端
            this.sendCurrentPositionToBackend();
          });

          // 获取当前位置失败的处理
          this.Geolocation.on('error', (err) => {
            console.error('获取当前位置失败：', err);
          });

          this.map.addControl(this.Geolocation);
        })
        .catch((err) => {
          // 错误处理
          console.error('地图加载失败：', err);
        });
    },
    // 发送当前位置到后端的方法
    sendCurrentPositionToBackend() {
      const position = {
        lng: this.currentLng,
        lat: this.currentLat
      };
      console.log("经纬度：" + JSON.stringify(position));
      axios.post(`/jiedan/riderQueue/driverAddress?id=${this.id}&driverLon=${position.lng}&driverLat=${position.lat}`)
        .then((res) => {
          console.log('当前位置已成功发送到后端', res);
        })
        .catch((error) => {
          console.error('发送当前位置到后端失败', error);
        });
    },
    // 标记点
    setMapMarker() {
      // 省略部分代码...
      // 逆解析地址
      this.toGeoCoder();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    xingc() {
      this.$router.push("/Trip")
    },
    // 逆解析地址
    toGeoCoder() {
      let lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete") {
          this.form.address = result.regeocode.formattedAddress;
        } else {
          this.form.address = '';
        }
      });
    },
    mounted() {
    }
  }
};
</script>

<style scoped>
.shouj {
}

#container {
  width: 100%;
  height: 650px;
}
.el-icon-chat-dot-square {
  position: relative;
  top: 25px;
  font-size: 30px;
}
.shuju {
  //width: 100%;
  height: 100px;
  //margin-left: 10px;
  //float: left;
  //border-radius: 10px;
  //background-color: #FFFFFF;
  //background-color: #52b7fd;


  i {
    font-size: 40px;
    margin-top: 20px;
  }
}

.didian {
  width: 100%;
  height: 60px;

  span {
    font-size: 15px;
    line-height: 40px;
  }
}

ul {
  width: 200px;
  height: 100px;
  float: left;
}

.app {
  height: 120px;
  width: 100%;
  background-color: #FFFFFF;
  float: left;
}

.qu {
  font-size: 19px;
  float: left;
  margin-top: 10px;
  margin-left: 10px;
}

.xiao1 {
  float: left;
  margin-left: 10px;
}

.xiao2 {
  float: left;
  margin-left: 10px;
}

.butt {
  width: 80px;
  height: 30px;
  background-color: #52b7fd;
  color: #FFFFFF;
  border-radius: 5px;
  float: right;
  margin-top: -40px;
  margin-right: 10px;
  font-size: 12px;
}

.phones {
  width: 50px;
  height: 85px;
  float: left;
}

.shuzi {
  font-size: 35px;
}

.weihao {
  font-size: 20px;
}

.group {
  //width: 400px;
  //height: 80px;
  //background-color: #dedede;
  //float: left;
  //margin-left: 10px;
}

.daoda {
  width: 180px;
  height: 40px;
  background-color: #ff6700;
  border-radius: 30px;
  border: 0px;
  color: #FFFFFF;
  margin-right: 20px;
}

.infinite-list {
  width: 88%;
}

.jiedao {
  width: 180px;
  height: 40px;
  background-color: #00c7ff;
  border-radius: 30px;
  border: 0px;
  color: #FFFFFF;
}
</style>
